import axios from 'axios'
import errorCode from '@/utils/errorCode'
import { login } from "@/api/login";
const service = axios.create({
	baseURL: 'http://localhost:8085', // url = base url + request url
	timeout: 5000 // request timeout
})

service.interceptors.request.use(config => {

    if(config.url!=="/login"){
		config.headers.Authorization = 'Bearer ' + uni.getStorageSync('token');
	}else{
		config.headers.loginType = 'WeChat';
	}
	//检查微信授权是否过期
	wx.checkSession({
	   success:function(res){
		   let userInfo=uni.getStorageSync('userInfo');
		   if(userInfo!=null&&userInfo!=""){
			   return true;
		   }else{
			   uni.removeStorageSync('userInfo');
			   uni.navigateTo({
			   	url: '/pages/login'
			   })
			   return false
		   }
	   },
	   fail:function(res){
		    uni.removeStorageSync('userInfo');
			uni.navigateTo({
				url: '/pages/login'
			})
			return false
	   }
	})

  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof(value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401) {
		uni.login({
		    provider: 'weixin',
		    success: function(res) {
				
		        let code = res.code;
				let data={
					username:res.code,
					code: "WeChat",
					password:'WECHAT'
				}
				login(data).then(response => {
					console.log(response)
					if(response.code==200){
						uni.setStorageSync('token',response.data.token);
					}
				});
				
			},
			fail:function(res){
				uni.showToast({
					title: "系统接口请求超时",
					icon:'none',
					duration: 5000
				})
			}
		})
	  
     


    } else if (code === 500) {
      uni.showToast({
      	title: msg,
		icon:'none',
      	duration: 5000
      })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      uni.showToast({
      	title: msg,
		icon:'none',
      	duration: 5000
      })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
	uni.showToast({
		title: message,
		icon:'none',
		duration: 5000
	})
    return Promise.reject(error)
  }
)

service.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}


export default service
